package com.liu.juc;

/**
 *
 * 生产者和消费者模型案例
 *
 *
 */
public class TestProductAndConsumer {


    public static void main(String[] args) {

        Saler saler = new Saler();

        ProductforSale pro = new ProductforSale(saler);
        Consumer consumer = new Consumer(saler);


        for (int i = 0; i <10 ; i++) {
            new Thread(pro,"生产者 A").start();
            new Thread(consumer,"消费者 B").start();
        }



    }


}

// 生产者

class ProductforSale implements  Runnable {

    private Saler saler;

   public    ProductforSale(Saler saler){
     this.saler=saler;
    }


    @Override
    public void run() {

       for (int i =0;i<20;i++){
           saler.getproduct();//
       }

    }
}

//消费者
class Consumer implements Runnable{

    private Saler saler;


    public Consumer(Saler saler) {
        this.saler = saler;
    }


    @Override
    public void run() {
        for (int i = 0; i <20 ; i++) {
            saler.saleproduct();
        }
    }
}

//店员
class Saler {

    private int product=0 ;

//    进货
    public synchronized void  getproduct() {
        if(product >=10){
            System.out.println("仓库已满");

            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

        System.out.println(" 进货"+Thread.currentThread().getName()+"-------  "+ ++product);
        this.notifyAll();


    }


    //    销售
    public synchronized void  saleproduct(){
        if (product<=0){

            System.out.println("缺货中。。。");
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(" 进货"+Thread.currentThread().getName()+"-------  "+ --product);
        this.notifyAll();





    }




}